package org.jash.shop2111.entry

import androidx.databinding.BaseObservable
import androidx.databinding.Bindable
import androidx.databinding.Observable
import androidx.databinding.Observable.OnPropertyChangedCallback
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableList
import androidx.databinding.ObservableList.OnListChangedCallback
import org.jash.shop2111.BR

class Cart:BaseObservable() {
    val cartItems = ObservableArrayList<CartItem>()
    init {
        cartItems.addOnListChangedCallback(object : OnListChangedCallback<ObservableList<CartItem>>() {
            override fun onChanged(sender: ObservableList<CartItem>?) {
            }

            override fun onItemRangeChanged(
                sender: ObservableList<CartItem>?,
                positionStart: Int,
                itemCount: Int
            ) {
            }

            override fun onItemRangeInserted(
                sender: ObservableList<CartItem>?,
                positionStart: Int,
                itemCount: Int
            ) {
                sender?.subList(positionStart, positionStart + itemCount)?.forEach {
                    it.addOnPropertyChangedCallback(object : OnPropertyChangedCallback() {
                        override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
                            if (propertyId in listOf(BR.count, BR.check)) {
                                notifyPropertyChanged(BR.allChecked)
                                notifyPropertyChanged(BR.total)
                            }
                        }
                    })
                }
            }

            override fun onItemRangeMoved(
                sender: ObservableList<CartItem>?,
                fromPosition: Int,
                toPosition: Int,
                itemCount: Int
            ) {
            }

            override fun onItemRangeRemoved(
                sender: ObservableList<CartItem>?,
                positionStart: Int,
                itemCount: Int
            ) {
                notifyPropertyChanged(BR.allChecked)
                notifyPropertyChanged(BR.total)
            }
        })
    }
    @get:Bindable
    @set:Bindable
    var allChecked:Int
        get() = when(cartItems.filter(CartItem::check).size) {
            0 -> 0
            cartItems.size -> 1
            else -> 2
        }
        set(value) {
            if (value != 2) {
                cartItems.forEach { it.check = value == 1}
            }
        }
    @get:Bindable
    val total
        get() = cartItems.filter(CartItem::check).map { it.goods_default_price * it.count }.sum()
}